import { deletePageById, editPageData, newPageData, postPageListData } from '@/services/main/system/system'
import { defineStore } from 'pinia'
import type { ISystemStore } from './type'

const useSystemStore = defineStore('system', {
  state: (): ISystemStore => ({
    currentPage: 1,
    pageSize: 10,
    loading: false,
    pageList: [],
    pageTotalCount: 0
  }),
  actions: {
    async postPageListAction(pageName: string, queryInfo: any) {
      try {
        this.loading = true
        const res = await postPageListData(pageName, queryInfo)
        if (res.code == 0) {
          this.pageList = res.data.list
          this.pageTotalCount = res.data.totalCount
        } else {
          return Promise.reject(new Error(`获取列表失败, 请联系管理员`))
        }
      } catch (error) {
        return Promise.reject(new Error(`获取列表失败, 请联系管理员`))
      } finally {
        this.loading = false
      }
    },
    async deletePageByIdAction(pageName: string, id: number) {
      try {
        const res = await deletePageById(pageName, id)
        if (res.code == 0) {
          const size = this.pageSize
          const offset = (this.pageList.length > 0 ? this.currentPage - 1 : this.currentPage - 2) * size
          ElMessage.success('删除成功')
          this.postPageListAction(pageName, { size, offset })
          this.pageSize = size
          this.currentPage = this.pageList.length > 0 ? this.currentPage : this.currentPage - 1
        } else {
          return Promise.reject(new Error(`删除失败, 请联系管理员`))
        }
      } catch (error) {
        return Promise.reject(new Error(`删除失败, 请联系管理员`))
      }
    },
    async newPageDataAction(pageName: string, pageInfo: any) {
      try {
        const res = await newPageData(pageName, pageInfo)
        if (res.code == 0) {
          this.postPageListAction(pageName, { offset: 0, size: 10 })
          this.currentPage = 1
          this.pageSize = 10
        } else {
          return Promise.reject(new Error(`新建失败, 请联系管理员`))
        }
      } catch (error) {
        return Promise.reject(new Error(`新建失败, 请联系管理员`))
      }
    },
    async editPageDataAction(pageName: string, id: number, pageInfo: any) {
      try {
        const res = await editPageData(pageName, id, pageInfo)
        if (res.code == 0) {
          const size = this.pageSize
          const offset = (this.currentPage - 1) * size
          this.postPageListAction(pageName, { size, offset })
          this.pageSize = size
          // this.currentPage =
        } else {
          return Promise.reject(new Error(`修改失败, 请联系管理员`))
        }
      } catch (error) {
        return Promise.reject(new Error(`修改失败, 请联系管理员`))
      }
    }
  }
})

export default useSystemStore
